import scipy.stats as stats
import datetime
import matplotlib.pyplot as plt
import matplotlib as mpl
import mpl_finance as mpf
from matplotlib.pylab import date2num
from matplotlib.pylab import  num2date
"""
相关序列分析
"""

import csv
from itertools import islice

def date_to_num(dates):
    date_time = datetime.datetime.strptime(dates,'%Y/%m/%d')
    num_time = date2num(date_time)
    return num_time

#candle_data 日期, 开盘,收盘,最高,最低,成交量,代码
def init_data():
    input_file = open("../data_origin/data.csv")
    csv_data = []
    candle_data = []
    for line in islice(input_file, 1, None):
        datas = line.split(',')
        csv_data.append(datas)
    csv_data = csv_data[::-1]
    for datas in csv_data:
        date = datas[0]
        open_price = float(datas[1])
        high_price = float(datas[2])
        low_price = float(datas[3])
        close_price = float(datas[4])

        candle_data.append([date_to_num(date),open_price,close_price,high_price,low_price])

    return candle_data


"""----------------绘图-----------------------"""
def draw_ochl_pic(candle_data,start1,end1,start2,end2):
    fig = plt.figure()
    ax = fig.add_subplot(121)
    title1 = "from {} to {}".format(num2date(start1),num2date(end1))
    ax.set_title(title1)
    print(start1,end2,start2,end2)
    # 左边图片
    c1 = [u for u in candle_data if u[0] >= start1 and u[0] <= end1]
    mpf.candlestick_ochl(ax, c1, width=0.6, colorup='r', colordown='g', alpha=1.0)
    
    #右边图片
    title2 = "from {} to {}".format(num2date(start2),num2date(end2))
    ax2 = fig.add_subplot(122)
    c2 = [u for u in candle_data if u[0] >= start2 and u[0] <= end2]
    print('c2',c2)
    ax2.set_title(title2)
    mpf.candlestick_ochl(ax2, c2, width=0.6, colorup='r', colordown='g', alpha=1.0)

    # 设置日期刻度旋转的角度 
    plt.xticks(rotation=0)
    #plt.title('from {} to {}'.format(csv_data[0][0],csv_data[30][0]))
    plt.xlabel('Date')
    plt.ylabel('Price')
    # x轴的刻度为日期
    #ax.xaxis_date()
    plt.show()

# 生成一个序列
def find_series(candle_data,start,space,lens=0):
    """
    这里如果给了space并且给了lens，那就是从开始取lens根数据
    如果给了space没有给lens,就是从start取到start+sapce
    start 用data_to_num转化过的日期
    space 时间跨度(天)
    lens 要取几根组合
    """
    l = []
    end = start + space

    for d in candle_data:
        ds  = d[0]
        open_price = d[1]
        high_price = d[3]
        low_price = d[4]
        close_price = d[2]

        end = start + space
        if lens != 0:
            end = 999999
        if ds >= start and ds <= end:
            if open_price > close_price:
                l.append(high_price)
                l.append(low_price)
            else:
                l.append(low_price)
                l.append(high_price)
        if lens != 0 and len(l) >= lens:
            break
    if len(l) == 0:
        print('未在指定日期找到数据 start={},space={},len={}'.format(num2date(start),space,lens))
        pass
    return l
        

def find_relevance(candle_data,dates,space):
    to_find = find_series(candle_data,dates,space)

    max_relevan = 0
    max_date_num = 0
    for i in range(len(candle_data)):
        _date = dates + i
        now = datetime.datetime.now()

        if _date > date2num(now):
            break
        #ipdb.set_trace()
        l = find_series(candle_data,_date,space,len(to_find))
        if len(l) != len(to_find):
            continue
        #比较相关性
        pear = stats.pearsonr(to_find,l)[0]
        if pear == 1:
            continue
        if max_relevan < pear:
            max_relevan = pear
            max_date_num = _date
    start1 = dates 
    end1= start1 + space;
    print('最大相关系数',max_relevan)
    start2 = max_date_num
    end2 = max_date_num+space

    # 绘制图像
    #draw_ochl_pic(candle_data,start1,end1+1,start2,end2+1)
    isSame = False
    # 找到间隔后下一天的收盘价
    next_close = 0
    for index,c in enumerate(candle_data):
        if c[0] >= end1 + 1:
            now_close = candle_data[index+1][2] 
            next_close = c[2]
            print('预测值为',next_close,'预测值升降',next_close - now_close)
            # 打印一下实际值
            real_unit = [d for d in candle_data if d[0] >= end1 ][0]
            # 找出真实值的索引
            real_prev_index = candle_data.index(real_unit)
            # 找出真实值昨天的收盘价
            real_prev_yeasterday_unit = candle_data[real_prev_index - 1]
            real_prev_yeasterday_close = real_prev_yeasterday_unit[2]
            print('真实值升降',real_unit[2] - real_prev_yeasterday_close )
            if (next_close - now_close > 0 and real_unit[2] - real_prev_yeasterday_close >0 ) or (next_close - now_close < 0 and real_unit[2] - real_prev_yeasterday_close <0 ):
                isSame = True
                print('相同')
            break
    return isSame
# 初始化数据
candle_data = init_data()
dates = date_to_num('2017/09/21')
same_num = 0
for i in range(0,20):
    isSame = find_relevance(candle_data,dates+i,3)
    if isSame:
        same_num += 1
print('same num',same_num)



